﻿using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraSplashScreen;
using Lanting.Utilities.NetConn;
using Lanting.Model.Util;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Net;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using System.Collections;
using System.Linq;
using DevExpress.XtraEditors.Controls;
using Lanting.Model;

namespace Lanting.Utilities
{
    public class UtilMethods
    {
        #region 声明-设置父窗体
        /// 动态dll声明-设置父窗体
        [DllImport("user32")]
        public static extern int SetParent(int child, int parent);
        #endregion

        #region 常用方法-程序异常处理
        public static void CatchException(Exception ex)
        {
            if (ex != null)
            {
                if (ex.StackTrace != null)
                {
                    if (ex.Message != "在创建窗口句柄之前，不能在控件上调用 Invoke 或 BeginInvoke。")
                    {
                        //ShowMessage(ex);
                    }
                    LogHelper.WriteLog(ex.Message + ":" + ex.StackTrace, "APPException");
                }
                else
                {
                    LogHelper.WriteLog(ex.Message, "APPException");
                    ShowMessage(ex);
                }
            }
            else
            {
                LogHelper.WriteLog("空异常", "APPException");
                ShowMessage("空异常");
            }
        }

        public static void CatchException(string exStr)
        {
            if (!String.IsNullOrEmpty(exStr))
            {
                LogHelper.WriteLog(exStr, "APPException");
            }
        }
        public static void AutoException(string exStr)
        {
            if (!String.IsNullOrEmpty(exStr))
            {
                LogHelper.WriteLog(exStr, "AutoException");
            }
        }
        public static void BusinessException(string exStr)
        {
            if (!String.IsNullOrEmpty(exStr))
            {
                LogHelper.WriteLog(exStr, "BusinessException");
            }
        }
        public static void SettingsException(string exStr)
        {
            if (!String.IsNullOrEmpty(exStr))
            {
                LogHelper.WriteLog(exStr, "SettingsException");
            }
        }
        public static void HoneyWellException(string exStr)
        {
            if (!String.IsNullOrEmpty(exStr))
            {
                LogHelper.WriteLog(exStr, "HoneyWellException");
            }
        }
        public static void CatchNHException(string exStr)
        {
            if (!String.IsNullOrEmpty(exStr))
            {
                LogHelper.WriteLog(exStr, "NHException");
            }
        }

        public static void UpBusinessException(string exStr)
        {
            if (!String.IsNullOrEmpty(exStr))
            {
                LogHelper.WriteLog(exStr, "UpBusinessException");
            }
        }

        public static void ovensLog(string exStr)
        {
            if (!String.IsNullOrEmpty(exStr))
            {
                LogHelper.WriteLog(exStr, "OvensLog");
            }
        }
        #endregion

        #region 常用方法-写入业务日志
        public static void Function_SaveLog(String logStr)
        {
            if (!String.IsNullOrEmpty(logStr))
            {
                LogHelper.WriteLog(logStr, "info");
            }
        }
        #endregion

        #region 常用方法-Json对象转Obj
        public static object Function_JsonConvert_ToObj<O>(object jsonObj)
        {
            string str_obj = JsonConvert.SerializeObject(jsonObj);
            return JsonConvert.DeserializeObject<O>(str_obj);
        }
        #endregion

        #region 常用方法-Json对象转List
        public static List<L> Function_JsonConvert_ToList<L>(object jsonObj)
        {
            string str_obj = JsonConvert.SerializeObject(jsonObj);
            JsonSerializer serializer = new JsonSerializer();
            StringReader strReader = new StringReader(str_obj);
            object o = serializer.Deserialize(new JsonTextReader(strReader), typeof(List<L>));
            return o as List<L>;
        }
        #endregion

        #region 常用方法-服务器访问
        /// <summary>
        ///  常用方法-服务器访问
        /// </summary>
        /// <typeparam name="O">obj类</typeparam>
        /// <typeparam name="L">list类</typeparam>
        /// <param name="obj_Params">参数</param>
        /// <param name="action">服务器方法</param>
        /// <returns></returns>
        public static Result Function_HttpPost<O, L>(string action, object obj_Params)
        {
            Params.acu.appKey = Function_GetNewAppkey(Params.acu.appKey);
            return NetUtils.HttpPost<O, L>(Params.serverUrl + action, (Dictionary<string, string>)obj_Params, Params.timeout_net, null, Encoding.UTF8, null);
        }
        #endregion

        #region 常用方法-服务器访问-自动生成Acu
        /// <summary>
        /// 常用方法-服务器访问-自动生成Acu
        /// </summary>
        /// <typeparam name="O"></typeparam>
        /// <typeparam name="L"></typeparam>
        /// <param name="action"></param>
        /// <param name="obj_Params"></param>
        /// <returns></returns>
        public static Result Function_HttpPost_WithAcu<O, L>(string action, object obj_Params)
        {
            //拼装acu参数
            Dictionary<string, string> mparams = (Dictionary<string, string>)obj_Params;
            mparams.Add("acu.appKey", Params.acu.appKey);
            mparams.Add("acu.userId", Params.acu.userId.ToString());
            mparams.Add("acu.id", Params.acu.id.ToString());
            //更新appKey
            Params.acu.appKey = Function_GetNewAppkey(Params.acu.appKey);
            return NetUtils.HttpPost<O, L>(Params.serverUrl + action, (Dictionary<string, string>)obj_Params, Params.timeout_net, null, Encoding.UTF8, null);
        }
        #endregion

        #region 常用方法-服务器访问-无Acu
        /// <summary>
        ///  常用方法-服务器访问
        /// </summary>
        /// <typeparam name="O">obj类</typeparam>
        /// <typeparam name="L">list类</typeparam>
        /// <param name="obj_Params">参数</param>
        /// <param name="action">服务器方法</param>
        /// <returns></returns>
        public static Result Function_HttpPost_WithOutAcu<O, L>(string action, object obj_Params)
        {
            return NetUtils.HttpPost<O, L>(Params.serverUrl + action, (Dictionary<string, string>)obj_Params, Params.timeout_net, null, Encoding.UTF8, null);
        }
        #endregion

        #region 常用方法-服务器访问-上传文件-自动生成Acu
        /// <summary>
        /// 常用方法-服务器访问-上传文件-自动生成Acu
        /// </summary>
        /// <param name="action">服务器方法</param>
        /// <param name="filePath">本地路径</param>
        /// <param name="fileName">服务器上另存名</param>
        /// <param name="obj_Params">参数</param>
        /// <returns></returns>
        public static Result Function_HttpPostFile_WithAcu<O, L>(string action, string filePath, object obj_Params)
        {
            //拼装acu参数
            Dictionary<string, string> mparams = (Dictionary<string, string>)obj_Params;
            mparams.Add("acu.appKey", Params.acu.appKey);
            mparams.Add("acu.userId", Params.acu.userId.ToString());
            mparams.Add("acu.id", Params.acu.id.ToString());
            mparams.Add("acu.end", "end");
            //更新appKey
            Params.acu.appKey = Function_GetNewAppkey(Params.acu.appKey);

            string fileName = "";
            if (!String.IsNullOrEmpty(filePath))
            {
                int pos = filePath.LastIndexOf("\\");
                fileName = filePath.Substring(pos + 1);
            }
            return NetUtils.Upload_Request<O, L>(Params.serverUrl + action, filePath, fileName, mparams);
        }
        #endregion

        #region 常用方法-Http-Appkey算法
        public static string Function_GetNewAppkey(string oldAppkey)
        {
            return Function_GetMD5(oldAppkey);
        }
        #endregion

        #region 常用方法-Http-获取MD5
        public static string Function_GetMD5(String input)
        {
            string cl = input;
            string pwd = "";
            MD5 md5 = MD5.Create();//实例化一个md5对像
                                   // 加密后是一个字节类型的数组，这里要注意编码UTF8/Unicode等的选择　
            byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(cl));
            // 通过使用循环，将字节类型的数组转换为字符串，此字符串是常规字符格式化所得
            for (int i = 0; i < s.Length; i++)
            {
                // 将得到的字符串使用十六进制类型格式。格式后的字符是小写的字母，如果使用大写（X）则格式后的字符是大写字符 

                pwd = pwd + s[i].ToString("X2");

            }
            return pwd;
        }
        #endregion

        #region 常用方法-Dev-显示提示框
        public static void ShowMessage(Exception ex)
        {
            XtraMessageBox.Show(ex.Message, "异常", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }
        public static void ShowMessage(string msg)
        {
            //this.Invoke(new MessageBoxShow(MessageBoxShow_F), new object[] { msg });
            //ShowMessage(msg, MessageType.Default);
            XtraMessageBox.Show(msg, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
        public static void ShowMessage(string title, string msg)
        {
            XtraMessageBox.Show(msg, title, MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        delegate void MessageBoxShow(string msg);
        public static void MessageBoxShow_F(string msg)
        {
            XtraMessageBox.Show(msg, "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
        #endregion

        #region 常用方法-Dev-打开新窗体
        /// <summary>
        /// 打开新窗体
        /// </summary>
        /// <param name="newForm">新窗体</param>
        /// <param name="baseForm">框架窗体</param>
        public static void Function_OpenForm(XtraForm newForm, XtraForm baseForm)
        {
            //开启等待窗体
            SplashScreenManager.ShowDefaultWaitForm("请等待", "窗体加载中");
            newForm.MinimizeBox = false;
            newForm.MaximizeBox = false;
            //新窗体初始化
            SetParent((int)newForm.Handle, (int)baseForm.Handle);
            //窗体位置
            newForm.Location = new Point(baseForm.Width / 2 - newForm.Width / 2, baseForm.Height / 2 - newForm.Height / 2);
            //显示新窗体
            newForm.Show();
            //关闭等待窗体
            SplashScreenManager.CloseDefaultWaitForm();
        }
        #endregion

        #region 常用方法-Dev-打开新窗体-大
        /// <summary>
        /// 打开新窗体
        /// </summary>
        /// <param name="newForm">新窗体</param>
        /// <param name="baseForm">框架窗体</param>
        public static void Function_OpenForm_Big(XtraForm newForm, XtraForm baseForm)
        {
            //开启等待窗体
            SplashScreenManager.ShowDefaultWaitForm("请等待", "窗体加载中");
            newForm.MinimizeBox = false;
            newForm.MaximizeBox = true;
            //新窗体初始化
            SetParent((int)newForm.Handle, (int)baseForm.Handle);
            //窗体位置
            newForm.Location = new Point(baseForm.Width / 2 - newForm.Width / 2, baseForm.Height / 2 - newForm.Height / 2);
            //newForm.Size = new Size(1265, 683);
            //显示新窗体
            newForm.Show();
            //关闭等待窗体
            SplashScreenManager.CloseDefaultWaitForm();
        }
        #endregion

        #region 常用方法-字节数组转2进制字符串-读线圈专用
        public static string Function_ConvertBytesToStringCoils(byte[] bytes)
        {
            string hexString = string.Empty;
            if (bytes != null)
            {
                StringBuilder strB = new StringBuilder();

                for (int i = bytes.Length - 1; i >= 0; i--)
                {
                    strB.Append(Convert.ToString(bytes[i], 2).PadLeft(8, '0'));
                }
                hexString = strB.ToString();
            }
            return hexString;
        }
        #endregion

        #region 常用方法-字节数组转2进制字符串-开关门状态专用
        public static string Function_ConvertBytesToStringCoilsL2H(byte[] bytes)
        {
            string hexString = string.Empty;
            if (bytes != null)
            {
                StringBuilder strB = new StringBuilder();

                for (int i = 0; i < bytes.Length; i++)
                {
                    strB.Append(Convert.ToString(bytes[i], 2).PadLeft(8, '0'));
                }
                hexString = strB.ToString();
            }
            return hexString;
        }
        #endregion

        #region 常用方法-字节数组转32位单精度浮点数
        public static float Function_ConvertToSingle(byte[] bytes)
        {
            if (bytes.Length >= 4)
            {
                bytes = bytes.Reverse().ToArray();
                byte[] bytes_new = new byte[4];
                bytes_new[0] = bytes[2];
                bytes_new[1] = bytes[3];
                bytes_new[2] = bytes[0];
                bytes_new[3] = bytes[1];
                return BitConverter.ToSingle(bytes_new, 0);
            }
            else
            {
                return 0;
            }
        }
        #endregion

        #region 常用方法-浮点数转字节数组
        public static byte[] Function_ConvertSingleToBytes(float value)
        {
            byte[] bytes = BitConverter.GetBytes(value).ToArray().Reverse().ToArray();
            byte[] bytes_new = new byte[4];
            bytes_new[0] = bytes[2];
            bytes_new[1] = bytes[3];
            bytes_new[2] = bytes[0];
            bytes_new[3] = bytes[1];
            return bytes_new;
        }
        #endregion

        #region 常用方法-字节数组转16进制字符串
        /// <summary>
        /// 常用方法-字节数组转16进制字符串
        /// </summary>
        /// <param name="bytes">字节数组</param>
        /// <returns>16进制格式字符串</returns>
        public static string Function_ConvertBytesToString16(byte[] bytes) // 0xae00cf => "AE00CF"
        {
            string hexString = string.Empty;
            if (bytes != null)
            {
                StringBuilder strB = new StringBuilder();

                for (int i = 0; i < bytes.Length; i++)
                {
                    strB.Append(bytes[i].ToString("X2"));
                }
                hexString = strB.ToString();
            }
            return hexString;
        }
        #endregion

        #region 常用方法-字节数组转16进制字符串-空格分隔
        /// <summary>
        /// 常用方法-字节数组转16进制字符串 空格分隔
        /// </summary>
        /// <param name="bytes">字节数组</param>
        /// <returns>16进制格式字符串(含空格)</returns>
        public static string Function_ConvertBytesToString16_WithBlock(byte[] bytes) // 0xae00cf => "AE 00 CF "
        {
            string hexString = string.Empty;
            if (bytes != null)
            {
                StringBuilder strB = new StringBuilder();

                for (int i = 0; i < bytes.Length; i++)
                {
                    strB.Append(bytes[i].ToString("X2"));
                    strB.Append(" ");
                }
                hexString = strB.ToString();
            }
            return hexString;
        }
        #endregion

        #region 常用方法-16进制字符串转字节数组
        /// <summary>
        /// 常用方法-16进制格式字符串转字节数组
        /// </summary>
        /// <param name="hexString">16进制格式字符串</param>
        /// <param name="discarded"></param>
        /// <returns></returns>
        public static byte[] Function_ConvertString16ToBytes(string hexString)
        {
            int discarded = 0;
            string newString = "";
            char c;
            // remove all none A-F, 0-9, characters
            for (int i = 0; i < hexString.Length; i++)
            {
                c = hexString[i];
                if (IsHexDigit(c))
                    newString += c;
                else
                    discarded++;
            }
            // if odd number of characters, discard last character
            if (newString.Length % 2 != 0)
            {
                discarded++;
                newString = newString.Substring(0, newString.Length - 1);
            }

            int byteLength = newString.Length / 2;
            byte[] bytes = new byte[byteLength];
            string hex;
            int j = 0;
            for (int i = 0; i < bytes.Length; i++)
            {
                hex = new String(new Char[] { newString[j], newString[j + 1] });
                bytes[i] = HexToByte(hex);
                j = j + 2;
            }
            return bytes;
        }

        private static bool IsHexDigit(char c)
        {
            //是否HexDigit
            return true;
        }

        private static byte HexToByte(string hex)
        {
            byte tt = byte.Parse(hex, System.Globalization.NumberStyles.HexNumber);
            return tt;
        }
        #endregion

        #region 常用方法-10进制数字转为16进制字符串
        public static string Function_Convert10IntTo16Str(Int64 int10, int bytesCount)
        {
            string str = int10.ToString("X" + bytesCount * 2);
            //长度不足 左补1个字符串长度
            if (str.Length % 2 != 0)
            {
                str = str.PadLeft(str.Length + 1, '0');
            }
            return str;
        }
        #endregion

        #region 常用方法-16进制字符串转为10进制数
        public static Int64 Function_Convert16StrTo10Int(string str16)
        {
            Int64 tempInt = Int32.Parse(str16, System.Globalization.NumberStyles.HexNumber);
            return tempInt;
        }
        #endregion

        #region 常用方法-高8位低8位字节数组转换
        private static byte[] Function_ExchangeByteArray(byte[] bytes)
        {
            byte[] realBytes = new byte[bytes.Length];
            if (bytes.Length % 2 == 0)
            {
                //高8位低8位对调 最终正确数组  0a 01 ba bb -> 01 0a bb ba  从左到右依次高位
                for (int i = 0; i < bytes.Length / 2; i++)
                {
                    realBytes[i * 2] = bytes[i * 2 + 1];
                    realBytes[i * 2 + 1] = bytes[i * 2];
                }
                return realBytes;
            }
            //非偶数对 返回原值
            else
            {
                return bytes;
            }
        }
        #endregion

        #region 常用方法-高16位低16位字节数组转换
        private static byte[] Function_Exchange16ByteArray(byte[] bytes)
        {
            byte[] realBytes = new byte[bytes.Length];
            if (bytes.Length % 2 == 0)
            {

                for (int i = 0; i < bytes.Length / 2; i++)
                {
                    realBytes[i * 2] = bytes[i * 2 + 2];
                    realBytes[i * 2 + 1] = bytes[i * 2];
                }
                return realBytes;
            }
            //非偶数对 返回原值
            else
            {
                return bytes;
            }
        }
        #endregion

        #region 常用方法-字符串转16进制字节数组
        /// <summary>
        /// 字符串转16进制字节数组
        /// </summary>
        /// <param name="hexString"></param>
        /// <returns></returns>
        public static byte[] strToToHexByte(string hexString)
        {

            if ((hexString.Length % 2) != 0)
            {
               // hexString += " ";//空格
                                 //throw new ArgumentException("s is not valid chinese string!");
            }

            System.Text.Encoding chs = System.Text.Encoding.GetEncoding("gb2312");

            byte[] bytes = chs.GetBytes(hexString);
            return bytes;
        }
        #endregion

        #region 常用方法-文件-下载服务器文件到桌面
        public static int Function_DownloadFile(string URL, string filepath, string filename)
        {
            try
            {
                System.Net.HttpWebRequest Myrq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(URL);
                System.Net.HttpWebResponse myrp = (System.Net.HttpWebResponse)Myrq.GetResponse();
                System.IO.Stream st = myrp.GetResponseStream();
                System.IO.Stream so = new System.IO.FileStream(filepath, System.IO.FileMode.Create);
                byte[] by = new byte[1024];
                int osize = st.Read(by, 0, (int)by.Length);
                while (osize > 0)
                {
                    so.Write(by, 0, osize);
                    osize = st.Read(by, 0, (int)by.Length);
                }
                so.Close();
                st.Close();
                ShowMessage("已保存到桌面,文件名为[" + filename + "]");
                return 1;
            }
            catch (Exception ex)
            {
                CatchException(ex);
                return 0;
            }
        }
        #endregion

        #region 常用方法-文件-打开文件浏览框选中并返回文件路径-Excel
        public static string Function_GetLocalFile_Excel()
        {
            try
            {
                string filePath = "";
                OpenFileDialog oFD = new OpenFileDialog();
                oFD.Title = "打开文件";
                oFD.ShowHelp = true;
                oFD.Filter = "Microsoft Excel files(*.xls)|*.xls;*.xlsx";  //过滤格式
                oFD.FilterIndex = 1;    //格式索引
                oFD.RestoreDirectory = true;    //记住上次路径
                oFD.InitialDirectory = "c:\\"; //默认路径
                oFD.Multiselect = false;    //多选

                filePath = "";
                if (oFD.ShowDialog() == DialogResult.OK)
                {
                    filePath = oFD.FileName;
                }
                return filePath;
            }
            catch (Exception ex)
            {
                throw;
            }
        }
        #endregion

        #region 常用方法-文件-获取文件数据流(根据文件路径、文件名)
        /// <summary>
        /// 常用方法-获取文件数据流(根据文件路径、文件名)
        /// </summary>
        /// <param name="ftpUrl">FTP地址</param>
        /// <param name="fileName">文件名</param>
        /// <returns></returns>
        public static Stream Function_GetFileStream(string ftpUrl)
        {
            try
            {
                HttpWebRequest reqWeb = (HttpWebRequest)HttpWebRequest.Create(new Uri(ftpUrl));
                HttpWebResponse respWeb = (HttpWebResponse)reqWeb.GetResponse();
                Stream stream = respWeb.GetResponseStream();
                //FtpWebRequest reqFtp = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpUrl + "" + fileName));
                //reqFtp.UseBinary = true;
                //FtpWebResponse respFtp = (FtpWebResponse)reqFtp.GetResponse();
                //Stream stream = respFtp.GetResponseStream();
                return stream;
            }
            catch (Exception)
            {
                throw;
            }
        }
        #endregion

        #region 常用方法-判断控件值非空-Text
        public static bool Function_ControlsTextNotNull(List<ControlInfo> controlNameList, Form form)
        {
            if (controlNameList != null)
            {
                foreach (ControlInfo fmControl in controlNameList)
                {
                    Control control = form.Controls.Find(fmControl.name, true)[0];
                    string text = (string)control.GetType().GetProperty("Text").GetValue(control, null);
                    if (string.IsNullOrEmpty(text))
                    {
                        ShowMessage(fmControl.label + "不能为空");
                        return false;
                    }
                }
            }
            return true;
        }
        #endregion

        #region 常用方法-根据控件名找到窗体控件
        public static Control Function_FindControlByName(XtraForm from, string controlName)
        {
            try
            {
                Control[] _controls = from.Controls.Find(controlName, true);
                if (_controls != null && _controls.Length >= 1)
                {
                    return _controls[0];
                }
                else
                {
                    CatchException("未找到窗体控件" + controlName);
                    return null;
                }
            }
            catch (Exception ex)
            {
                CatchException(ex);
                return null;
            }
        }
        #endregion

        #region 常用方法-Url编码-UTF8
        public static string Function_UrlEncode(string str)
        {
            if (String.IsNullOrEmpty(str))
            {
                return str;
            }
            else
            {
                StringBuilder sb = new StringBuilder();
                byte[] byStr = Encoding.UTF8.GetBytes(str);
                Regex regKey = new Regex("^[A-Za-z0-9]+$");
                for (int i = 0; i < byStr.Length; i++)
                {
                    string strBy = Convert.ToChar(byStr[i]).ToString(CultureInfo.InvariantCulture);
                    if (regKey.IsMatch(strBy))
                    {
                        //是字母或者数字则不进行转换  
                        sb.Append(strBy);
                    }
                    else
                    {
                        //sb.Append(@"%" + Convert.ToString(byStr[i], 16).ToUpper());
                        sb.Append(@"%" + byStr[i].ToString("X2"));
                    }
                }
                return (sb.ToString());
            }

        }
        #endregion

        #region 常用方法-获取List中元素字符串
        /// <summary>
        /// 获取List中元素字符串
        /// </summary>
        /// <typeparam name="L"></typeparam>
        /// <param name="list">数据集合</param>
        /// <param name="split">分隔符</param>
        /// <param name="propertiyName">属性名</param>>
        /// <returns></returns>
        public static string Function_GetListItems<L>(List<L> list, string split, string propertiyName)
        {
            string str_return = "";
            if (list != null && list.Count > 0)
            {
                var properties = list.GetType().GetGenericArguments()[0].GetProperties();
                int i = properties.FindIndex(v => v.Name == propertiyName);
                if (i >= 0)
                {
                    foreach (L l in list)
                    {
                        str_return += properties[i].GetValue(l, null) + split;
                    }
                    if (!String.IsNullOrEmpty(str_return))
                    {
                        str_return = str_return.Substring(0, str_return.Length - 1);
                    }
                    return str_return;
                }
                else
                {
                    return "";
                }
            }
            else
            {
                return "";
            }
        }
        #endregion

        #region 常用方法-网络通信-通信是否成功
        public static bool Function_HttpStatus(Result result, string alertMessage)
        {
            try
            {
                if (result != null)
                {
                    //成功
                    if (result.status == Params.status_ok)
                    {
                        return true;
                    }
                    //失败
                    else
                    {
                        ShowMessage(alertMessage + "失败", result.info);
                        return false;
                    }
                }
                else
                {
                    ShowMessage(alertMessage + "异常");
                    return false;
                }
            }
            catch (Exception ex)
            {
                CatchException(ex);
                return false;
            }
        }
        #endregion

        #region 常用方法-下拉框数据绑定
        public static void Function_ComboBoxBindData(ComboBoxEdit combo, List<ComboInfo> list, int id, int value, string text)
        {
            if (list != null && list.Count > 0)
            {
                combo.Properties.Items.Clear();
                foreach (ComboInfo util in list)
                {
                    combo.Properties.Items.Add(util);
                }
                ComboInfo selectedinfo = null;
                //编辑
                if (id > 0)
                {
                    if (value != 0)
                    {
                        selectedinfo = list.Find(v => v.value == value.ToString());
                    }
                    else if (!String.IsNullOrEmpty(text))
                    {
                        selectedinfo = list.Find(v => v.text == text);
                    }
                }
                //新增
                else
                {
                    selectedinfo = list[0];
                }
                if (selectedinfo != null)
                {
                    combo.SelectedItem = selectedinfo;
                }
            }
        }
        #endregion

        

        #region 常用方法-下拉框数据绑定-默认选全部
        public static void Function_ComboBoxBindData_All(ComboBoxEdit combo, List<ComboInfo> list)
        {
            combo.Properties.Items.Clear();
            combo.Properties.Items.Add(new ComboInfo("全部", ""));
            combo.SelectedIndex = 0;
            if (list != null && list.Count > 0)
            {
                foreach (ComboInfo info in list)
                {
                    combo.Properties.Items.Add(info);
                }
            }
        }
        #endregion

        #region 常用方法-多选下拉框数据绑定
        public static void Function_ChckedComboBoxBindData(CheckedComboBoxEdit combo, List<ComboInfo> list, string ids, string names)
        {
            if (list != null && list.Count > 0)
            {
                combo.Properties.Items.Clear();
                string[] array_ids = null, array_names = null;
                if (!String.IsNullOrEmpty(ids))
                {
                    //拆分ids
                    array_ids = ids.Split(',');
                }
                else if (!String.IsNullOrEmpty(names))
                {
                    //拆分names
                    array_names = names.Split(',');
                }

                foreach (ComboInfo util in list)
                {
                    CheckedListBoxItem item = new CheckedListBoxItem(util.value, util.text, CheckState.Unchecked);
                    if (array_ids != null && array_ids.Length > 0)
                    {
                        for (int i = 0; i < array_ids.Length; i++)
                        {
                            if (item.Value != null && item.Value.ToString().Equals(array_ids[i].Trim()))
                            {
                                item.CheckState = CheckState.Checked;
                                break;
                            }
                        }
                    }
                    else if (array_names != null && array_names.Length > 0)
                    {
                        for (int i = 0; i < array_names.Length; i++)
                        {
                            if (item.Description != null && item.Description.Equals(array_names[i].Trim()))
                            {
                                item.CheckState = CheckState.Checked;
                                break;
                            }
                        }
                    }

                    combo.Properties.Items.Add(item);
                }
                combo.RefreshEditValue();
            }
        }
        #endregion

        #region 常用方法-获取下拉框选中值
        public static void Function_GetComboBoxValue(ComboBoxEdit combo, out int value, out string text)
        {
            value = 0;
            text = "";
            if (combo.SelectedIndex >= 0)
            {
                value = Int32.Parse(((ComboInfo)combo.Properties.Items[combo.SelectedIndex]).value);
                text = ((ComboInfo)combo.Properties.Items[combo.SelectedIndex]).text;
            }
        }
        #endregion

        #region 常用方法-获取下拉框选中值
        public static string Function_GetComboBoxValue(ComboBoxEdit combo)
        {
            if (combo.SelectedIndex >= 0)
            {
                return ((ComboInfo)combo.Properties.Items[combo.SelectedIndex]).value;
            }
            else
            {
                return "";
            }
        }
        #endregion

        #region 常用方法-获取下拉框选中Info
        public static string Function_GetComboBoxInfo(ComboBoxEdit combo)
        {
            if (combo.SelectedIndex >= 0)
            {
                return ((ComboInfo)combo.Properties.Items[combo.SelectedIndex]).info;
            }
            else
            {
                return "";
            }
        }
        #endregion

        #region 常用方法-获取下拉框选中Text
        public static string Function_GetComboBoxText(ComboBoxEdit combo)
        {
            if (combo.SelectedIndex >= 0)
            {
                return ((ComboInfo)combo.Properties.Items[combo.SelectedIndex]).text;
            }
            else
            {
                return "";
            }
        }
        #endregion

        

        #region 常用方法-获取多选下拉框选中值
        public static void Function_GetCheckedComboBoxValues(CheckedComboBoxEdit combo, out string values, out string texts)
        {
            values = "";
            texts = "";
            for (int i = 0; i < combo.Properties.Items.Count; i++)
            {
                if (combo.Properties.Items[i].CheckState == CheckState.Checked)
                {
                    values += combo.Properties.Items[i].Value + ",";
                    texts += combo.Properties.Items[i].Description + ",";
                }
            }
            if (!String.IsNullOrEmpty(values))
            {
                values = values.Substring(0, values.Length - 1);
                texts = texts.Substring(0, texts.Length - 1);
            }
        }
        #endregion

        #region 常用方法-获取DateTime?类型值
        public static string Function_getStrFromDateTime(DateTime? datetime)
        {
            if (datetime.HasValue)
            {
                return datetime.Value.ToString("yyyy-MM-dd");
            }
            else
            {
                return "";
            }
        }
        #endregion

        #region 常用方法-获取DateEdit控件值
        public static string Function_getStrFromDateEdit(DateEdit edit, string format)
        {
            if (!string.IsNullOrEmpty(edit.Text) && edit.DateTime != null)
                return edit.DateTime.ToString(format);
            else
                return "";
        }
        #endregion

        #region 常用方法-获取DateEdit控件值
        public static string Function_getStrFromDateEdit_Date(DateEdit edit)
        {
            if (!string.IsNullOrEmpty(edit.Text) && edit.DateTime != null)
                return edit.DateTime.ToString("yyyy-MM-dd") + " 23:59:59";
            else
                return "";
        }
        #endregion

        #region 常用方法-文本框非空判断
        public static bool Function_getTextEditIsNull(TextEdit text)
        {
            if (text.Text != string.Empty)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        #endregion

        #region 常用方法-串口线程-线程是否成功
        public static bool Function_PortThreadStatus(Result result, string alertMessage)
        {
            try
            {
                if (result != null)
                {
                    //成功
                    if (result.status == Params.status_ok)
                    {
                        return true;
                    }
                    //失败
                    else
                    {
                        BusinessException(alertMessage + "失败" + result.info);
                        return false;
                    }
                }
                else
                {
                    BusinessException(alertMessage + "异常");
                    return false;
                }
            }
            catch (Exception ex)
            {
                CatchException(ex);
                return false;
            }
        }
        #endregion

        #region 常用方法-判断列表是否为空
        public static bool Function_ListNotNull(IList list)
        {
            if (list != null && list.Count > 0)
                return true;
            else
                return false;
        }
        #endregion

        public static double Function_StringToDouble(string text)
        {
            double i = 0;
            if (!string.IsNullOrEmpty(text))
            {
                i = double.Parse(text);
            }
            return i;
        }

    }
}
